package vista;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class GridExtend extends JScrollPane implements ActionListener
{
	private static final long serialVersionUID = 1L;
	private JTableButtonModel grd_Model;
	private JTable grid;
	private List<GridExtendActionListener> listeners;
	
	public GridExtend(Vector<String> columnas, Vector<String> botones)
	{
		grd_Model = new JTableButtonModel(columnas, botones);
		listeners = new ArrayList<GridExtendActionListener>();
		
		ButtonRenderer render = new ButtonRenderer();
		grid = new JTable();
		grid.setDefaultRenderer(JButton.class, render);
		grid.setModel(grd_Model);
		grid.setPreferredScrollableViewportSize(new Dimension(500, 70));
				
		for (int i=0; i<botones.size(); i++ )
			grid.getColumn(botones.elementAt(i)).setCellEditor(new ButtonEditor(this));
		
		super.setViewportView(grid);
	}
	
	public void setScrollableSize(int width, int height)
	{
		grid.setPreferredScrollableViewportSize(new Dimension(width, height));
	}
	
	public void setBounds(int x, int y, int width, int height)
	{
		super.setBounds(x, y, width, height);
		setScrollableSize(width, height);
	}
	
	public void addRow(Vector<Object> row)
	{
		((JTableButtonModel)grid.getModel()).addRow( row );
	}
	
	public void clear()
	{
		((JTableButtonModel)grid.getModel()).Clear();
		grid.updateUI();
	}
	
	public void resize(int x, int y)
	{
		// DO NOTHING
	}

	public void addActionListener(GridExtendActionListener listener)
	{
		listeners.add(listener);
	}
	
	public void removeActionListener(GridExtendActionListener listener)
	{
		listeners.remove(listener);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		JButton button = (JButton) e.getSource();
		
		String label = button.getText();
		Object id = button.getActionCommand();
		GridExtendEvent ev = null;
		
		if (label.compareTo("Ver") == 0)
			ev = new GridExtendEvent(this, id, Accion.Ver);
		else if (label.compareTo("Editar") == 0)
			ev = new GridExtendEvent(this, id, Accion.Editar);
		else if (label.compareTo("Eliminar") == 0)
			ev = new GridExtendEvent(this, id, Accion.Eliminar);
		else if (label.compareTo("Seleccionar") == 0)
			ev = new GridExtendEvent(this, id, Accion.Seleccionar);
		
		for(GridExtendActionListener listener : listeners){
			listener.actionPerformed(ev);
		}
	}
}
